#!/usr/bin/env python3
"""初始化数据库脚本"""
import sys
import os

# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from app.database import engine, Base
from app.models import (
    ScanTask,
    ScanRecord,
    Issue,
    FieldConfig,
    ConfirmHistory,
    ScanRecordExtension,
    ScanIssueExtension,
)
from app.config import settings

def init_database():
    """初始化数据库"""
    print("正在创建数据库表...")
    Base.metadata.create_all(bind=engine)
    print("✅ 数据库表创建成功！")
    
    # 初始化扫描任务数据
    from sqlalchemy.orm import sessionmaker
    SessionLocal = sessionmaker(bind=engine)
    db = SessionLocal()
    
    try:
        # 检查是否已有数据
        existing_tasks = db.query(ScanTask).count()
        if existing_tasks > 0:
            print(f"✅ 数据库中已有 {existing_tasks} 个扫描任务，跳过初始化")
            return
        
        # 创建初始扫描任务
        tasks = [
            ScanTask(
                name="鸿蒙仓颉API设计规范扫描",
                task_type="harmony_api_scan",
                description="扫描鸿蒙仓颉API设计规范问题",
                status="enabled"
            ),
            ScanTask(
                name="arkTS接口一致性校验扫描",
                task_type="arkts_consistency_scan",
                description="校验arkTS接口一致性",
                status="enabled"
            ),
            ScanTask(
                name="cjd源码一致性扫描",
                task_type="cjd_consistency_scan",
                description="扫描cjd源码一致性问题",
                status="enabled"
            ),
        ]
        
        for task in tasks:
            db.add(task)
        
        db.commit()
        print("✅ 初始扫描任务数据创建成功！")
        print(f"   - {tasks[0].name}")
        print(f"   - {tasks[1].name}")
        print(f"   - {tasks[2].name}")
        
        # 创建字段配置（多代码片段支持）
        print("\n正在创建字段配置...")
        
        # 获取任务ID
        harmony_task = db.query(ScanTask).filter(ScanTask.task_type == "harmony_api_scan").first()
        arkts_task = db.query(ScanTask).filter(ScanTask.task_type == "arkts_consistency_scan").first()
        cjd_task = db.query(ScanTask).filter(ScanTask.task_type == "cjd_consistency_scan").first()
        
        # arkTS一致性扫描任务的代码片段字段配置
        if arkts_task:
            arkts_code_fields = [
                FieldConfig(
                    task_id=arkts_task.id,
                    field_name="cangjie_code_snippet",
                    display_name="Cangjie代码片段",
                    field_type="code",
                    field_category="issue_extension",
                    display_order=10,
                    show_in_list=False,
                    show_in_detail=True,
                    help_text="Cangjie代码片段，用于对比展示"
                ),
                FieldConfig(
                    task_id=arkts_task.id,
                    field_name="arkts_code_snippet",
                    display_name="ArkTS代码片段",
                    field_type="code",
                    field_category="issue_extension",
                    display_order=11,
                    show_in_list=False,
                    show_in_detail=True,
                    help_text="ArkTS代码片段，用于对比展示"
                ),
            ]
            for field in arkts_code_fields:
                # 检查是否已存在
                existing = db.query(FieldConfig).filter(
                    FieldConfig.task_id == field.task_id,
                    FieldConfig.field_name == field.field_name
                ).first()
                if not existing:
                    db.add(field)
            print("  ✅ arkTS一致性扫描任务代码片段字段配置已创建")
        
        # cjd一致性扫描任务的代码片段字段配置
        if cjd_task:
            cjd_code_fields = [
                FieldConfig(
                    task_id=cjd_task.id,
                    field_name="old_value_code",
                    display_name="旧值代码",
                    field_type="code",
                    field_category="issue_extension",
                    display_order=10,
                    show_in_list=False,
                    show_in_detail=True,
                    help_text="旧值代码片段，用于对比展示"
                ),
                FieldConfig(
                    task_id=cjd_task.id,
                    field_name="new_value_code",
                    display_name="新值代码",
                    field_type="code",
                    field_category="issue_extension",
                    display_order=11,
                    show_in_list=False,
                    show_in_detail=True,
                    help_text="新值代码片段，用于对比展示"
                ),
            ]
            for field in cjd_code_fields:
                # 检查是否已存在
                existing = db.query(FieldConfig).filter(
                    FieldConfig.task_id == field.task_id,
                    FieldConfig.field_name == field.field_name
                ).first()
                if not existing:
                    db.add(field)
            print("  ✅ cjd一致性扫描任务代码片段字段配置已创建")
        
        db.commit()
        print("✅ 字段配置创建成功！")
        
    except Exception as e:
        db.rollback()
        print(f"❌ 初始化数据失败: {e}")
        raise
    finally:
        db.close()

if __name__ == "__main__":
    try:
        init_database()
        print("\n✅ 数据库初始化完成！")
    except Exception as e:
        print(f"\n❌ 数据库初始化失败: {e}")
        sys.exit(1)

